package com.hnblc.blcwms.rest.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hnblc.blcwms.common.constant.StringPool;
import com.hnblc.blcwms.common.exceptions.ErrorDescription;
import com.hnblc.blcwms.common.exceptions.GeneralException;
import com.hnblc.blcwms.common.interaction.Response;
import com.hnblc.blcwms.common.interaction.RestResponse;
import com.hnblc.blcwms.common.utils.encrypt.BASE64;
import com.hnblc.blcwms.persistent.interfaces.business.entity.DefinitionLog;
import com.hnblc.blcwms.persistent.interfaces.business.service.IDefinitionLogService;
import com.hnblc.blcwms.persistent.interfaces.client.dto.CurrentClient;
import com.hnblc.blcwms.persistent.interfaces.client.entity.ClientAuth;
import com.hnblc.blcwms.persistent.interfaces.message.entity.MessageLog;
import com.hnblc.blcwms.rest.dto.restInteraction.EncryptRequest;
import com.hnblc.blcwms.rest.service.IMessageService;
import com.hnblc.blcwms.serviceapi.api.dto.WareHouseOperate;
import com.hnblc.blcwms.serviceapi.api.dto.definition.ArticleCategory;
import com.hnblc.blcwms.serviceapi.api.dto.definition.ArticleInfo;
import com.hnblc.blcwms.serviceapi.api.dto.definition.BaseDefinition;
import com.hnblc.blcwms.serviceapi.api.dto.definition.Company;
import com.hnblc.blcwms.serviceapi.api.enums.code.CompanyTypeEnum;
import com.hnblc.blcwms.serviceapi.api.enums.code.DefinitionLogTypeEnum;
import com.hnblc.blcwms.serviceapi.api.enums.result.definition.CompanyResultEnum;
import com.hnblc.blcwms.serviceapi.api.group.owner.OwnerGroup;
import com.hnblc.blcwms.serviceapi.api.group.owner.definition.DefArticleGroup;
import com.hnblc.blcwms.serviceapi.api.group.owner.definition.DefCategoryGroup;
import com.hnblc.blcwms.serviceapi.api.service.IDefinitionAPIService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

@Setter
@Getter
@RestController
@RequestMapping("blc/wms/api")
@Api(value="基础资料REST API",description = "线上店铺、门店、供应商、商品类别、商品信息等相关操作",tags={"基础资料接口"})
@Validated
public class DefinitionAPI extends BaseRestAPI{

    private Logger logger = LoggerFactory.getLogger(DefinitionAPI.class);
    @Autowired
    IDefinitionAPIService definitionAPIService;

    @Autowired
    IMessageService messageService;

    @Autowired
    IDefinitionLogService definitionLogService;

    @ApiOperation(value="创建运营单位", notes="创建货主、电商、供应商基础单位",position = 1)
    @RequestMapping(value = "/company/create",method = RequestMethod.POST)
    @ResponseBody
    public RestResponse createCompany(@Validated(OwnerGroup.class)@RequestBody EncryptRequest message, HttpServletRequest request) throws IOException {
        //测试打印原始报文
        String jsonString = IOUtils.toString(request.getInputStream(), Charset.defaultCharset());
        logger.debug("***********************************create Categories test start***************************\n"+jsonString+"\n*********************end*************************");

        //解析业务数据 从BASE64字符串解析为JSON字符串，再解析为业务对象
        Company company;
        try {

            company = objectMapper.readValue(new String(BASE64.decryptBASE64(message.getBusinessData()), StringPool.CHARSET_UTF8),new TypeReference<Company>() { });
        }catch (Exception e){
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_BAD_PARAMETER_FORMAT_0,e));
        }

        //简单验证
        this.validate(company, OwnerGroup.class);

//        校验操作权限
//        ClientAuth clientAuth = this.buildAuth(message,businessData);
        ClientAuth clientAuth = new ClientAuth();
        clientAuth.setClientId(message.getClientId());
        clientAuth.setEnterpriseNo(company.getEnterpriseNo());
        clientAuth.setWarehouseNo("N");
        clientAuth.setOwnerNo("N");
//        货主权限，客户专用位
        clientAuth.setCustomNo("N");
        CurrentClient currentClient = this.clientInfoService.loadCurrentClient(clientAuth);
        if (null == currentClient || currentClient.getClientAuthInfo().size() < 1) {
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_CLIENT_UNAUTHORIZED_0));
        }

        //验签
        try {
            if (!this.signatureValidate(message, currentClient)) {
                return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_SIGNATURE_VALIDATE_FAIL_0));
            }
        } catch (Exception e) {
            logger.error("接口处理验签异常", e);
            throw new GeneralException(e);
        }
        MessageLog messageLog = messageService.process(currentClient, request);
        //根据不同企业类别创建对应的运营单位
        Response result = null;
        String companyType = company.getCompanyType();
        DefinitionLogTypeEnum logType;
        if(CompanyTypeEnum.OWNER.code().equals(companyType)){
            result = definitionAPIService.createOwner(company);
            logType = DefinitionLogTypeEnum.OWNER;
        }else if (CompanyTypeEnum.SUPPLIER.code().equals(companyType)){
            result= definitionAPIService.createSupplier(company);
            logType = DefinitionLogTypeEnum.SUPPLIER;
        }else if (CompanyTypeEnum.CUSTOM.code().equals(companyType)){
            result= definitionAPIService.createCustomForSell(company);
            logType = DefinitionLogTypeEnum.CUSTOM;
        }else if (CompanyTypeEnum.OWNER_WITH_CUSTOM.code().equals(companyType)){
            result = definitionAPIService.createOwnerWithCustom(company);
            logType = DefinitionLogTypeEnum.OWNER_WITH_CUSTOM;
        }else {
            return new RestResponse(new Response(CompanyResultEnum.WRONG_COMPANY_TYPE));
        }
        DefinitionLog companyLog = new DefinitionLog(logType.code(),clientAuth.getClientId(),messageLog.getSeqNo(),company.getSheetId(),result);
        definitionLogService.save(companyLog);
        messageService.processed(messageLog);

        return new RestResponse(result);
    }


    @ApiOperation(value="批量创建商品基础资料", notes="批量创建商品基础信息",position = 3)
    @RequestMapping(value = "/article/create",method = RequestMethod.POST)
    @ResponseBody
    public RestResponse<Boolean> createArticleInfo(@Validated(DefArticleGroup.class)@RequestBody EncryptRequest message, HttpServletRequest request) throws IOException {
        //测试打印原始报文
        String jsonString = IOUtils.toString(request.getInputStream(), Charset.defaultCharset());
        logger.debug("***********************************ArticleInfo create test start***************************\n"+jsonString+"\n*********************end*************************");

        //解析业务数据 从BASE64字符串解析为JSON字符串，再解析为业务对象
        WareHouseOperate<BaseDefinition<List<ArticleInfo>>> businessData;

        try {
            businessData = objectMapper.readValue(new String(BASE64.decryptBASE64(message.getBusinessData()), StringPool.CHARSET_UTF8),new TypeReference<WareHouseOperate<BaseDefinition<List<ArticleInfo>>>>() { });
        }catch (Exception e){
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_BAD_PARAMETER_FORMAT_0,e));
        }

        //简单验证
        this.validate(businessData, DefArticleGroup.class);

        //校验操作权限
        ClientAuth clientAuth = this.buildAuth(message,businessData);
        //货主权限，客户专用位
        clientAuth.setCustomNo("N");
        CurrentClient currentClient = this.clientInfoService.loadCurrentClient(clientAuth);
        if (null == currentClient || currentClient.getClientAuthInfo().size() < 1) {
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_CLIENT_UNAUTHORIZED_0));
        }

        //验签
        try {
            if (!this.signatureValidate(message, currentClient)) {
                return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_SIGNATURE_VALIDATE_FAIL_0));
            }
        } catch (Exception e) {
            logger.error("接口处理验签异常", e);
            throw new GeneralException(e);
        }
        MessageLog messageLog = messageService.process(currentClient, request);

        //创建商品基础资料
        Response<List<ArticleInfo>> result= definitionAPIService.createArticleInfos(businessData.getOperateDetails(),currentClient.getClientAuthInfo().get(0));
        //保存消息日志
        DefinitionLog companyLog = new DefinitionLog(DefinitionLogTypeEnum.ARTICLE.code(),clientAuth.getClientId(),messageLog.getSeqNo(),businessData.getOperateDetails().getSheetId(),result);
        definitionLogService.save(companyLog);
        messageService.processed(messageLog);

        return new RestResponse(result);
    }

    @ApiOperation(value="批量创建商品类别", notes="批量创建商品基础资料",position = 2)
    @RequestMapping(value = "/category/create",method = RequestMethod.POST)
    @ResponseBody
    public RestResponse createArticleCategories(@Validated(DefCategoryGroup.class)@RequestBody EncryptRequest message, HttpServletRequest request) throws IOException {
        //测试打印原始报文
        String jsonString = IOUtils.toString(request.getInputStream(), Charset.defaultCharset());
        logger.debug("***********************************create Categories test start***************************\n"+jsonString+"\n*********************end*************************");

        //解析业务数据 从BASE64字符串解析为JSON字符串，再解析为业务对象
        WareHouseOperate<BaseDefinition<List<ArticleCategory>>> businessData;
        try {
            businessData = objectMapper.readValue(new String(BASE64.decryptBASE64(message.getBusinessData()), StringPool.CHARSET_UTF8),new TypeReference<WareHouseOperate<BaseDefinition<List<ArticleCategory>>>>() { });
        }catch (Exception e){
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_BAD_PARAMETER_FORMAT_0,e));
        }

        //简单验证
        this.validate(businessData, DefCategoryGroup.class);

        //校验操作权限
        ClientAuth clientAuth = this.buildOwnerAuth(message,businessData);
        CurrentClient currentClient = this.clientInfoService.loadCurrentClient(clientAuth);
        if (null == currentClient || currentClient.getClientAuthInfo().size() < 1) {
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_CLIENT_UNAUTHORIZED_0));
        }

        //验签
        try {
            if (!this.signatureValidate(message, currentClient)) {
                return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_SIGNATURE_VALIDATE_FAIL_0));
            }
        } catch (Exception e) {
            logger.error("接口处理验签异常", e);
            throw new GeneralException(e);
        }
        MessageLog messageLog = messageService.process(currentClient, request);
        //批量创建商品类别
        Response<List<ArticleCategory>> result= definitionAPIService.createCategories(businessData.getOperateDetails(),currentClient.getClientAuthInfo().get(0));
        //保存消息日志
        DefinitionLog companyLog = new DefinitionLog(DefinitionLogTypeEnum.ARTICLE_CATEGORY.code(),clientAuth.getClientId(),messageLog.getSeqNo(),businessData.getOperateDetails().getSheetId(),result);
        definitionLogService.save(companyLog);
        messageService.processed(messageLog);

        return new RestResponse(result);
    }


}
